<template>
  <c-back-wrap :loading="loading" go-page="市场开发/升级月度任务跟进" :before-call-back="$goBackCall" current-page="编辑">
    <QupFormContainer :column="3">
      <el-form ref="form" :model="formData" :rules="formRules" label-width="120px">
        <el-form-item prop="taskCode" label="店面升级改造任务号">
          <span>{{ ctmShopReformTaskFollowUpDTO.taskCode }}</span>
        </el-form-item>
        <el-form-item prop="dataSource" label="数据来源">
          <c-dict-range-view :value="ctmMarketDTO.dataSource" dict-type-code="CTM_MARKET_DATA_FROM" domain-code="marketing" app-code="slm" />
        </el-form-item>
        <el-form-item prop="dataSourceMsg" label="数据来源描述">
          <span>{{ ctmMarketDTO.dataSourceMsg }}</span>
        </el-form-item>
        <el-form-item prop="appraisalPlan" label="考核计划">
          <c-dict-range-view :value="ctmMarketDTO.appraisalPlan" dict-type-code="CTM_APPRAISAL_PLAN" domain-code="marketing" app-code="slm" />
        </el-form-item>
        <el-form-item prop="taskDate" label="任务日期">
          <span>{{ ctmShopReformTaskFollowUpDTO.taskDate }}</span>
        </el-form-item>
        <el-form-item prop="taskType" label="任务类型">
          <c-dict-range-view :value="ctmMarketDTO.taskType" dict-type-code="CTM_MARKET_TASK_TYPE" domain-code="marketing" app-code="slm" />
        </el-form-item>
        <el-form-item prop="marketCode" label="市场编码">
          <span>{{ ctmMarketDTO.marketCode }}</span>
        </el-form-item>
        <el-form-item prop="marketName" label="市场名称">
          <span>{{ ctmMarketDTO.marketName }}</span>
        </el-form-item>
        <el-form-item prop="marketType" label="市场类型">
          <c-dict-range-view :value="ctmMarketDTO.marketType" dict-type-code="TOBE_MARKET_TYPE" domain-code="marketing" app-code="slm" />
        </el-form-item>
        <el-form-item prop="agencyCode" label="所属办事处编码">
          <span>{{ ctmMarketDTO.agencyCode }}</span>
        </el-form-item>
        <el-form-item prop="agencyName" label="办事处名称">
          <span>{{ ctmMarketDTO.agencyName }}</span>
        </el-form-item>
        <el-form-item prop="customerCode" label="客户">
          <c-common-search-dis
            v-model="formData.customerCode"
            :label.sync="formData.customerName"
            :disabled="!ctmMarketDTO.agencyCode"
            :depend-on-observe="ctmMarketDTO.agencyCode"
            :start-observe="startObserve"
            :one-category-code_res.sync="oneCategoryCode"
            :before-params="paramsJson => {
              paramsJson.filtersRaw.push({ id: 'agencyCode', property: 'agencyCode', value: ctmMarketDTO.agencyCode, operator: '=' })
              $codeOrName(paramsJson.filtersRaw, 'code', 'name')
              return paramsJson
            }"
            @change="handleCustomerChange"
          />
        </el-form-item>
        <el-form-item prop="customerName" label="客户编码">
          <span>{{ formData.customerCode }}</span>
        </el-form-item>
        <el-form-item prop="shopCode" label="门店名称">
          <c-common-search-shop
            v-if="ctmMarketDTO.marketType==='A'"
            v-model="formData.shopCode"
            :label.sync="formData.shopName"
            :format-label="v => {
              return `${v.name}(${v.code})`
            }"
            :disabled="!formData.customerCode"
            :depend-on-observe="formData.customerCode"
            :start-observe="startObserve"
            :customer-code="formData.customerCode"
            :before-params="paramsJson=>{
              paramsJson.filtersRaw.push({id:'status',property:'status',value:'1',operator:'='})
              paramsJson.filtersRaw.push({id:'agencyCode',property:'agencyCode',value: ctmMarketDTO.agencyCode,operator:'='})
              $codeOrName(paramsJson.filtersRaw, 'code', 'name')
              return paramsJson
            }"
            @change="handleShopChange"
          />
          <span v-else>{{ formData.shopName }}</span>
        </el-form-item>
        <el-form-item prop="shopName" label="门店编码">
          <span>{{ formData.shopCode }}</span>
        </el-form-item>
        <template v-if="showOldCustomerCode">
          <el-form-item key="originalCustomerCode" prop="originalCustomerCode" label="原商家客户编码">
            <c-common-search-dis
              v-model="formData.originalCustomerCode"
              :label.sync="formData.originalCustomerName"
              :format-label="v => {
                return v.code
              }"
              :disabled="!ctmMarketDTO.agencyCode"
              :depend-on-observe="ctmMarketDTO.agencyCode"
              :start-observe="startObserve"
              :filters-raw="[{id:'status',property:'status',value:'[1,0]', operator: 'IN'}]"
              :before-params="paramsJson => {
                paramsJson.filtersRaw.push({ id: 'agencyCode', property: 'agencyCode', value: ctmMarketDTO.agencyCode, operator: '=' })
                $codeOrName(paramsJson.filtersRaw, 'code', 'name')
                return paramsJson
              }"
            />
          </el-form-item>
          <el-form-item key="originalCustomerName" prop="originalCustomerName" label="原商家客户名称">
            <span>{{ formData.originalCustomerName }}</span>
          </el-form-item>
        </template>
        <el-form-item prop="responsibleCode" label="责任人编码">
          <span>{{ ctmShopReformTaskFollowUpDTO.responsibleCode }}</span>
        </el-form-item>
        <el-form-item prop="responsibleName" label="责任人姓名">
          <span>{{ ctmShopReformTaskFollowUpDTO.responsibleName }}</span>
        </el-form-item>
        <el-form-item prop="responsiblePhone" label="责任人联系电话">
          <span>{{ ctmShopReformTaskFollowUpDTO.responsiblePhone }}</span>
        </el-form-item>
        <el-form-item prop="shopBuildNumber" label="门店建设项目号">
          <c-common-search-shop-build
            v-model="formData.shopBuildNumber"
            :label="formData.shopBuildNumber"
            :const-type.sync="formData.shopBuildType"
            :const-schedule.sync="formData.shopBuildStage"
            :disabled="!formData.shopCode"
            :depend-on-observe="formData.shopCode"
            :start-observe="startObserve"
            :before-params="paramsJson=>{
              const filtersRaw = [{id:'shopCode',property:'shopCode',value:formData.shopCode,operator:'='}]
              paramsJson.filtersRaw?paramsJson.filtersRaw.push(...filtersRaw):(paramsJson.filtersRaw=filtersRaw)
              return paramsJson
            }"
          />
        </el-form-item>
        <el-form-item prop="shopBuildType" label="门店建设类型">
          <c-dict-select v-model="formData.shopBuildType" dict-type-code="CONST_TYPE" clearable placeholder="门店建设类型" style="width:100%" />
        </el-form-item>
        <el-form-item prop="shopBuildStage" label="门店整体建设进度">
          <c-dict-range-view v-model="formData.shopBuildStage" dict-type-code="BEFORE_CONST_SCHEDULE" />
        </el-form-item>
        <el-form-item prop="marketFollowUpStage" label="市场跟进进度">
          <c-dict-select v-model="formData.marketFollowUpStage" dict-type-code="CTM_MARKET_BUID_PROGRESS" clearable placeholder="市场建设进度" style="width:100%" />
        </el-form-item>
        <el-form-item prop="createTime" label="分配时间">
          <span>{{ ctmShopReformTaskFollowUpDTO.createTime }}</span>
        </el-form-item>
        <el-form-item prop="enable" label="启用状态">
          <c-dict-range-view :value="[1,'1'].includes(ctmShopReformTaskFollowUpDTO.enable)?'启用':'停用'" />
        </el-form-item>
        <el-form-item prop="settlementTime" label="结案日期">
          <el-date-picker v-model="formData.settlementTime" type="date" value-format="yyyy-MM-dd HH:mm:ss" placeholder="结案日期" @change="handleSettlementDateChange" />
        </el-form-item>
        <el-form-item prop="settlementMethod" label="结案方式">
          <c-dict-select v-model="formData.settlementMethod" dict-type-code="CTM_CLOSED_TYPE" clearable placeholder="结案方式" style="width:100%" />
        </el-form-item>
        <el-form-item prop="remark" label="说明" :span="24">
          <el-input v-model="formData.remark" type="textarea" show-word-limit maxlength="1024" :autosize="{minRows: 2}" placeholder="说明" clearable />
        </el-form-item>
      </el-form>
    </QupFormContainer>
    <div class="btn-center">
      <c-button type="default" @click="handleCancel">取消</c-button>
      <c-button type="primary" @click="handleConfirm">确定</c-button>
    </div>
  </c-back-wrap>
</template>

<script>
import { detailMonthTask, editMonthTask, isUnCompleteWeekTask } from '@/api/channelTask2/monthTask'
export default {
  name: 'AddEdit',
  props: {
    id: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      oneCategoryCode: '', // 客户一级分类
      formData: {
        customerCode: '', //	客户编码
        customerName: '', //	客户名字
        originalCustomerCode: '', // 原商家
        originalCustomerName: '', // 原商家
        shopCode: '', //	门店编码
        shopName: '', //	门店名字
        shopBuildNumber: '', //	门店建设项目任务号
        shopBuildStage: '', //	门店建设进度
        shopBuildType: '', //	门店建设类型
        marketFollowUpStage: '', //	市场跟进进度
        settlementMethod: '', //	结案方式
        settlementTime: '', //	结案日期
        remark: '' //	说明
      },
      detail: {},
      startObserve: false,
      loading: false
    }
  },
  computed: {
    formRules() {
      // 70252   【待开发及整改月任务】当客户一级分类为“全友轻居客户”时，取消“门店名称”和“门店建设项目号”必填
      const isQyqjkh = this.oneCategoryCode === 'Z230'
      const { marketFollowUpStage, settlementTime } = this.formData
      const isEnd = marketFollowUpStage === 'C' && !isQyqjkh
      const isUnderway = marketFollowUpStage === 'C'
      // 【待开发及整改市场总表/月任务】当“结案日期”有值时，需控制“结案方式”必填
      const settlementMethodRequired = !!settlementTime
      return {
      // 市场建设进度值新增时默认为未开始，可手工修改，
      // 当市场建设进度为已完成时，结案日期、结案方式必填；
        settlementTime: [{ required: isUnderway, message: '请选择结案日期', trigger: 'change' }],
        settlementMethod: [{ required: isUnderway || settlementMethodRequired, message: '请选择结案方式', trigger: 'change' }],
        shopCode: [{ required: isUnderway, message: '请选择门店', trigger: 'change' }],
        // 当门店建设进度为“进行中”时，门店建设项目号必填，选择范围为当前门店下对应的门店建设整体进度不等于已终止的门店建设项目号；
        // 弹框显示字段：门店建设项目号、门门店建设整体进度；
        shopBuildNumber: [{ required: isUnderway, message: '请选择门店建设项目号', trigger: 'change' }]
      }
    },
    ctmMarketDTO() {
      return this.detail.ctmMarketDTO || {}
    },
    ctmShopBuildWeeklyTaskFollowUpDTOS() {
      return this.detail.ctmShopBuildWeeklyTaskFollowUpDTOS || []
    },
    ctmShopReformTaskFollowUpDTO() {
      return this.detail.ctmShopReformTaskFollowUpDTO || {}
    },
    // 显示原商家
    showOldCustomerCode() {
      const { marketType, marketNatrue } = this.ctmMarketDTO || {}
      return marketType === 'A' && marketNatrue === 'B'
    }
  },
  watch: {
    showOldCustomerCode: {
      handler(v) {
        if (!v) {
          this.$set(this.formData, 'originalCustomerCode', '')
          this.$set(this.formData, 'originalCustomerName', '')
        }
      }
    }
  },
  created() {
    this.getDetailData()
  },
  methods: {
    getDetailData() {
      this.loading = true
      return detailMonthTask(this.id).then(res => {
        this.loading = false
        this.detail = res.data
        this.initFormData()
        if (!this.formData.marketFollowUpStage) {
          this.$set(this.formData, 'marketFollowUpStage', 'A')
        }
        // setTimeout(() => {
        //   this.startObserve = true
        // }, 200)
      }).catch(() => {
        this.loading = false
      })
    },
    initFormData() {
      const tmp = {}
      const keys = Object.keys(this.formData)
      keys.forEach(k => {
        const v = this.detail.ctmMarketDTO[k]
        const v1 = this.detail.ctmShopReformTaskFollowUpDTO[k]
        tmp[k] = v !== undefined && v !== null ? v : (v1 !== undefined && v1 !== null ? v1 : '')
      })
      this.formData = tmp
    },
    handleSettlementDateChange(v) {
      if (v && this.formData.marketFollowUpStage !== 'C') {
        this._marketFollowUpStage = this.formData.marketFollowUpStage
        this.$set(this.formData, 'marketFollowUpStage', 'C')
      } else if (this._marketFollowUpStage) {
        this.$set(this.formData, 'marketFollowUpStage', this._marketFollowUpStage)
      }
    },
    handleCustomerChange() {
      this.$set(this.formData, 'shopCode', '')
      this.$set(this.formData, 'shopName', '')
      this.handleShopChange()
    },
    handleShopChange() {
      this.$set(this.formData, 'shopBuildNumber', '')
      this.$set(this.formData, 'shopBuildType', '')
      this.$set(this.formData, 'shopBuildStage', '')
    },
    handleCancel() {
      this.$goBackCall().then(this.$pageStack.pop)
    },
    handleConfirm() {
      return this.$refs.form.validate().then(async() => {
        if (['C', 'D'].includes(this.formData.marketFollowUpStage)) {
          await isUnCompleteWeekTask(this.id).then(res => {
            if ([1, '1'].includes(res.data)) {
              // this.$message.warning('当前月任务还有未完成的周任务，是否终止周任务并完结当前月任务？')
              return this.$msgbox({
                title: '提示',
                message: '当前月任务还有未完成的周任务，是否终止周任务并完结当前月任务？',
                showCancelButton: true,
                type: 'warning'
              })
            }
            return Promise.resolve(true)
          })
        }
        const data = { ...this.formData }
        data.id = this.id
        return editMonthTask(data).then(() => {
          this.$message.success('操作成功!')
          this.$pageStack.pop('opCondition')
        })
      })
    }
  }
}
</script>
